/*
 * create by Littleken at 2019/3/14 17:24
 */
package com.littleken.sellproject.service;

import com.littleken.sellproject.dao.OrderDetailMapper;
import com.littleken.sellproject.dao.OrderMasterMapper;
import com.littleken.sellproject.dto.CartDTO;
import com.littleken.sellproject.dto.OrderDTO;
import com.littleken.sellproject.enums.OrderStatusEnum;
import com.littleken.sellproject.enums.PayStatusEnum;
import com.littleken.sellproject.enums.ResultEnum;
import com.littleken.sellproject.exception.SellException;
import com.littleken.sellproject.model.OrderDetail;
import com.littleken.sellproject.model.OrderMaster;
import com.littleken.sellproject.model.ProductInfo;
import com.littleken.sellproject.utils.KeyUtil;
import com.littleken.sellproject.utils.converter.OrderMaster2OrderDTOConverter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderService {

    @Resource
    private OrderMasterMapper masterMapper;

    @Resource
    private OrderDetailMapper detailMapper;

    @Resource
    private ProductInfoService productInfoService;


    @Transactional
    public OrderDTO create(OrderDTO orderDTO){

        //用于记录订单总价
        BigDecimal orderAmount = new BigDecimal(BigInteger.ZERO);

        //生成订单id
        String orderId = KeyUtil.genUniqueKey();

        //1. 查询商品（数量, 价格）
        for (OrderDetail orderDetail : orderDTO.getOrderDetailList()){
            ProductInfo productInfo = productInfoService.findOne(orderDetail.getProductId());
            if(productInfo == null){
                //商品不存在异常
                throw new SellException(ResultEnum.CART_EMPTY.PRODUCT_NOT_EXIST);
            }

            //2. 计算订单总价
            orderAmount = productInfo.getProductPrice()
                    .multiply(new BigDecimal(orderDetail.getProductQuantity()))
                    .add(orderAmount);

            //数据库插入订单
            orderDetail.setDetailId(KeyUtil.genUniqueKey());
            orderDetail.setOrderId(orderId);
            BeanUtils.copyProperties(productInfo, orderDetail);
            detailMapper.save(orderDetail);

        }

        //3. 写入订单数据库（orderMaster和orderDetail）
        OrderMaster orderMaster = new OrderMaster();
        orderDTO.setOrderId(orderId);
        BeanUtils.copyProperties(orderDTO, orderMaster);
        orderMaster.setOrderAmount(orderAmount);
        orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
        orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());
        masterMapper.save(orderMaster);


        //4 扣库存
        List<CartDTO> cartDTOList  = orderDTO.getOrderDetailList().stream()
                .map(e -> new CartDTO(e.getProductId(),e.getProductQuantity()))
                .collect(Collectors.toList());
        productInfoService.subtractStock(cartDTOList);


        return orderDTO;
    }

    public OrderDTO findOne(String OrderID){
        OrderMaster orderMaster = new OrderMaster();
        try {
            orderMaster = masterMapper.findById(OrderID).get();
            //log.error("orderMaster={}",orderMaster);
           /* if(orderMaster == null){
                //抛订单不存在异常
                throw new SellException(ResultEnum. ORDER_NOT_EXIST);
            }*/
        }catch (NoSuchElementException e){
            throw new SellException(ResultEnum. ORDER_NOT_EXIST);
        }


        List<OrderDetail> orderDetailList =  detailMapper.findByOrderId(OrderID);
        if(CollectionUtils.isEmpty(orderDetailList)){
           throw new SellException(ResultEnum.ORDERDETAIL_NOT_EXIST);
        }

        OrderDTO orderDTO = new OrderDTO();
        BeanUtils.copyProperties(orderMaster,orderDTO);
        orderDTO.setOrderDetailList(orderDetailList);

        return orderDTO;
    }

    public Page<OrderDTO> findList(String buyerOpenid, Pageable pageable){
        Page<OrderMaster> orderMasterPage = masterMapper.findByBuyerOpenid(buyerOpenid,pageable);

        List<OrderDTO> orderDTOList = OrderMaster2OrderDTOConverter.convert(orderMasterPage.getContent());

        return new PageImpl<OrderDTO>(orderDTOList,pageable,orderMasterPage.getTotalElements());

    }

    public Page<OrderDTO> findList(Pageable pageable){
        Page<OrderMaster> orderMasterPage = masterMapper.findAll(pageable);

        List<OrderDTO> orderDTOList = OrderMaster2OrderDTOConverter.convert(orderMasterPage.getContent());

        return new PageImpl<OrderDTO>(orderDTOList,pageable,orderMasterPage.getTotalElements());
    }

    @Transactional
    public OrderDTO cancel(OrderDTO orderDTO){
        OrderMaster orderMaster = new OrderMaster();

        //判断订单状态
        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
            log.error("【取消订单】订单状态不正确, orderId={}, orderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }

        //修改订单状态
        orderDTO.setOrderStatus(OrderStatusEnum.CANCEL.getCode());
        BeanUtils.copyProperties(orderDTO, orderMaster);
        OrderMaster updateResult = masterMapper.save(orderMaster);
        if (updateResult == null) {
            log.error("【取消订单】更新失败, orderMaster={}", orderMaster);
            throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
        }

        //返回库存
        if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())) {
            log.error("【取消订单】订单中无商品详情, orderDTO={}", orderDTO);
            throw new SellException(ResultEnum.ORDER_DETAIL_EMPTY);
        }
        List<CartDTO> cartDTOList = orderDTO.getOrderDetailList().stream()
                .map(e -> new CartDTO(e.getProductId(), e.getProductQuantity()))
                .collect(Collectors.toList());
        productInfoService.addStock(cartDTOList);

        //如果已经支持，用户退款

        if (orderDTO.getPayStatus().equals(PayStatusEnum.SUCCESS.getCode())) {
            //payService.refund(orderDTO);
            //todo:没写用户退款
        }

        return orderDTO;
    }

    @Transactional
    public OrderDTO finish(OrderDTO orderDTO){
        //判断订单状态
        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
            log.error("【完结订单】订单状态不正确, orderId={}, orderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }
        //修改订单状态
        orderDTO.setOrderStatus(OrderStatusEnum.FINISHED.getCode());
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO, orderMaster);
        OrderMaster updateResult = masterMapper.save(orderMaster);
        if (updateResult == null) {
            log.error("【完结订单】更新失败, orderMaster={}", orderMaster);
            throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
        }

        return orderDTO;
    }

    @Transactional
    public OrderDTO paid(OrderDTO orderDTO){
        //判断订单状态
        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
            log.error("【订单支付完成】订单状态不正确, orderId={}, orderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }

        //判断支付状态
        if (!orderDTO.getPayStatus().equals(PayStatusEnum.WAIT.getCode())) {
            log.error("【订单支付完成】订单支付状态不正确, orderDTO={}", orderDTO);
            throw new SellException(ResultEnum.ORDER_PAY_STATUS_ERROR);
        }

        //修改支付状态
        orderDTO.setPayStatus(PayStatusEnum.SUCCESS.getCode());
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO, orderMaster);
        OrderMaster updateResult = masterMapper.save(orderMaster);
        if (updateResult == null) {
            log.error("【订单支付完成】更新失败, orderMaster={}", orderMaster);
            throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
        }

        return orderDTO;
    }

}
